import axios from "axios"
import router from "./router/index.js"
import Element from 'element-ui'

// axios.default.baseURL = "http://localhost:8080"

//创建一个axios
const request = axios.create({
	timeout: 5000,
	headers: {
		'Content-Type': 'application/json; charset=utf-8'
	}
})
// 请求头加上token
request.interceptors.request.use(config => {
	config.headers['Authorization'] = localStorage.getItem("token")
	return config
})

request.interceptors.response.use(response => {
	//正常情况200
		let res = response.data;
		if (res.code === 200) {
			return response
		} else {
			//弹窗错误情况，若错误信息为空就提示异常
			Element.Message.error(res.msg?res.msg:'系统异常' ,{
				duration: 3000
			})
			// 拒绝并显示原因
			return Promise.reject(response.data.msg)
		}
	},
	//其余异常情况
	error => {
		console.log(error)
		if (error.response.data) {
			error.message = error.response.data.msg
		}
		
		if (error.response.status === 401) {
			router.push("/login")
		}
		Element.Message.error(error.message, {
			duration: 3000
		})
		return Promise.reject(error)
	}
)

export default request
